package com.issac.handler;

import cn.hutool.json.JSONUtil;
import com.issac.common.R;
import com.issac.exception.CaptchaException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @ClassName LoginFailureHandler
 * @Author zy
 * @Date 2021/11/22 15:11
 * @Description LoginFailureHandler
 * @Version 1.0
 */
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException e) throws IOException, ServletException {

        response.setContentType("application/json,charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();
        R result;
        if (e instanceof CaptchaException){
            result = R.error("验证码错误");
        }else {
            result = R.error("账号或密码输入错误，请重新登录！");
        }
        outputStream.write(JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
